package com.game.sec;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import com.game.utils.SecStringUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * 进入controller之前解析body,一般用于消息内容的解密处理
 * 
 * @author ZGame
 *
 */
@ControllerAdvice
public class SecRequestBodyAdvice implements RequestBodyAdvice {
	@Value("${security.open}")
	private boolean openSecurity;

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return openSecurity;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		try {
			return new MyHttpInputMessage(inputMessage);
		} catch (Exception e) {
			e.printStackTrace();
			return inputMessage;
		}
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	class MyHttpInputMessage implements HttpInputMessage {
		private HttpHeaders headers;
		private InputStream body;

		public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
			this.headers = inputMessage.getHeaders();
			this.body = IOUtils.toInputStream(
					easpString(SecStringUtil.unSecString(IOUtils.toString(inputMessage.getBody(), "UTF-8"))));
		}

		@Override
		public InputStream getBody() throws IOException {
			return body;
		}

		@Override
		public HttpHeaders getHeaders() {
			return headers;
		}

		/**
		 *
		 * @param requestData
		 * @return
		 */
		public String easpString(String requestData) {
			requestData = JSONObject.parseObject(requestData).toJSONString();
			if (requestData != null && !requestData.equals("")) {
				if (!requestData.startsWith("{\"requestData\":")) {
					throw new RuntimeException("参数【requestData】缺失异常！");
				} else {
					int closeLen = requestData.length() - 1;
					int openLen = "{\"requestData\":".length();
					String result = StringUtils.substring(requestData, openLen, closeLen);
					return result;
				}
			}
			return "";
		}

	}
}
